using System;
using System.Collections.Generic;
using FluffyUnderware.DevTools;
using Unity.Collections;
using UnityEngine;

/// <summary>
/// 豪车场景专用,同时只会存在一个实体
/// </summary>
public class CarEntityController : MonoBehaviour
{
    private static CarEntityController m_instance;
    public static CarEntityController Instance
    {
        get { return m_instance; }
    }
    [ReadOnly]
    public string lightKeyword = "_ENABLEEMISSIVE_ON";
    [ReadOnly]
    public string lightMatPrefix = "_lamplight";
    [ReadOnly]
    public string lightShaderName = "GGame/HRP/Car/ClearCoat_Car";
    [SerializeField]
    [Label("车灯MeshRenderer")]
    private MeshRenderer lightRenderer;

    private Material tempMat;    
    
    private bool carLightIsOn = false;
    void Start()
    {
        carLightIsOn = false;
        m_instance = this;
    }

    public void EnableCarLight(bool lightIsOn)
    {
        carLightIsOn = lightIsOn;

        if (tempMat!= null)
        {
            if (carLightIsOn)
            {
                tempMat.EnableKeyword(lightKeyword);
            }
            else
            {
                tempMat.DisableKeyword(lightKeyword);
            }
            return;
        }
        
        if (lightRenderer != null)
        {
            Material[] sharedMats = lightRenderer.sharedMaterials;
            List<Material> sharedMatsList = new List<Material>(sharedMats.Length);
            lightRenderer.GetSharedMaterials(sharedMatsList);
            Material[] instancedMats = lightRenderer.materials;
            int matIdx = -1;
            for(int i=0;i<sharedMatsList.Count;++i)
            {
                if (sharedMatsList[i].shader.name != lightShaderName || !sharedMatsList[i].name.Contains(lightMatPrefix))
                {
                    Destroy(instancedMats[i]);
                    instancedMats[i] = sharedMatsList[i];
                }
                else
                {
                    tempMat = instancedMats[i];
                    matIdx = i;
                }
            }
            
            if (matIdx != -1)
            {
                if (carLightIsOn)
                {
                    tempMat.EnableKeyword(lightKeyword);
                }
                else
                {
                    tempMat.DisableKeyword(lightKeyword);
                }

                lightRenderer.materials = instancedMats;
            }
        }
    }

    public void SetLightMeshRenderer(MeshRenderer renderer)
    {
        lightRenderer = renderer;
    }

    private void OnDestroy()
    {
        if (tempMat != null)
        {
            Destroy(tempMat);
        }
    }
}

